import axios from 'axios';
import { notification } from 'antd';
import JavascriptCommon from './javascript.common';

//基础设置
axios.defaults.timeout = 1000 * 60 * 2;
axios.defaults.baseURL = 'http://api.crqcn.com';
axios.defaults.transformRequest = [
	data => {
		let ret = '';
		for (let it in data) {
			ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
		}
		return ret;
	},
];

// http请求拦截器
axios.interceptors.request.use(
	config => {
		config.headers = config.headers || {};
		if (JavascriptCommon.GetSysTokenSession('accessToken')) {
			config.headers['Access-Token'] = JavascriptCommon.GetSysTokenSession('accessToken');
			config.headers['Permit-Token'] = JavascriptCommon.GetSysTokenSession('permitToken');
		}
		return config;
	},
	err => {
		return Promise.reject(err);
	}
);

// http响应拦截器
axios.interceptors.response.use(
	response => {
		if ('access-token' in response.headers) {
			setTimeout(() => {
				JavascriptCommon.SetSysTokenSession('accessToken', response.headers['access-token']);
			}, 0);
		}
		if (typeof response.data === 'object') {
			if ('flag' in response.data) {
				if ('code' in response.data) {
					response.data.code = Number.parseInt(response.data.code);
					if (response.data.flag === 'False') {
						if (response.data.code === 0) {
							//警告
							if (response.data.message) {
								notification.warning({ message: response.data.message });
							}
						} else if (response.data.code === 1 && !/Backend_MenuTree/gi.test(response.config.url)) {
							//登录超时
							notification.warning({ message: '登录超时,请重新登录' });
							setTimeout(() => {
								sessionStorage.clear();
								window.location.replace('/');
							}, 1200);
						} else if (response.data.code === 2) {
							//没有权限
							//this.$router.push({ path: "/error" });
						} else {
							//todo
						}
					}
				}
			}
		}
		return response;
	},
	err => {
		return Promise.reject(err);
	}
);

export default axios;
